<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12" >
            <a-form-model-item label="编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" placeholder="请输入编号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="采购类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="meUnit">
              <j-dict-select-tag type="list" v-model="model.procurementType" dictCode="procurement_type" placeholder="请选择采购类型"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
<!--          <a-col :span="12" >-->
<!--            <a-form-model-item label="购货数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">-->
<!--              <a-input v-model="model.num" placeholder="请输入编号" ></a-input>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
          <a-col :span="12" >
<!--            <a-form-model-item label="运输方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">-->
<!--              <a-input v-model="model.transport" placeholder="请输入编号" ></a-input>-->
<!--            </a-form-model-item>-->
            <a-form-model-item label="运输方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="meUnit">
              <j-dict-select-tag type="list" v-model="model.transport" dictCode="transportation_method" placeholder="请选择运输方式"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="付款方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <j-dict-select-tag type="list" v-model="model.payment" dictCode="payment_method" placeholder="请选择付款方式"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12" >
            <a-form-model-item label="付款时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <j-dict-select-tag type="list" v-model="model.paymentTime" dictCode="payment_time" placeholder="请选择付款时间"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.type" placeholder="请输入类型" ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12" >
            <a-form-model-item label="到货描述" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.arrivalDesc" placeholder="请输入到货描述" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12"  >
            <a-form-model-item  label="采购人员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="procurementPerson">
              <a-input v-model="model.procurementPerson" placeholder=""  />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12"  >
            <a-form-model-item  label="其他事项" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-textarea v-model="model.otherRem" placeholder="" :rows="4" />
            </a-form-model-item>
          </a-col>
        </a-row>
<!--        <a-row>-->
<!--          <a-col :span="12" >-->
<!--            <a-form-model-item label="总价格" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">-->
<!--              <a-input v-model="model.allPrice" placeholder="请输入编号" ></a-input>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
<!--        </a-row>-->
<!--        <a-row justify="start">-->
<!--          -->
<!--        </a-row>-->
<!--          <a-row>-->
<!--            <a-col :span="12">-->
<!--              <a-button-->
<!--                type="primary"-->
<!--                icon="PlusCircleOutlined"-->
<!--                size="default"-->
<!--                @click="selectSupplier">-->
<!--                选择供应商-->
<!--              </a-button>-->
<!--            </a-col>-->
<!--          </a-row>-->
        <a-card  v-show='displaySupplier'>
          <a-row>
            <a-col :span="12" >
              <a-form-model-item label="供货单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
<!--                <a-input v-model="supplier.name" placeholder="" :disabled='true'></a-input>-->
                <a-input-search
                  v-model="supplier.name"
                  placeholder=""
                  style="width: 200px"
                  enter-button
                  @search="selectSupplier"
                  disabled
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12" >
              <a-form-model-item label="地址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
                <a-input v-model="supplier.address" placeholder="" disabled></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row >
            <a-col :span="12" >
              <a-form-model-item label="委托代理人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
                <a-input v-model="supplier.agent" placeholder="" disabled></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12" >
              <a-form-model-item label="电话" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
                <a-input v-model="supplier.telephone" placeholder="" disabled></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row >
            <a-col :span="12" >
              <a-form-model-item label="税号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
                <a-input v-model="supplier.code" placeholder="" disabled ></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12" >
              <a-form-model-item label="开户银行" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
                <a-input v-model="supplier.bankName" placeholder="" disabled></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row >
            <a-col :span="12" >
              <a-form-model-item label="账号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
                <a-input v-model="supplier.accountNo" placeholder="" disabled></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12" >
              <a-form-model-item label="邮编" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
                <a-input v-model="supplier.zipCode" placeholder="" disabled></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="原料采购订单明细" :key="refKeys[0]" :forceRender="true">
        <a-row justify="start" >
          <!-- 新增 -->
          <a-col :span="12">
            <a-space>
            <a-button
              type="primary"
              icon="PlusCircleOutlined"
              size="default"
              @click="addPlan"
              v-show='model.procurementType == 0'
            >
              计划新增
            </a-button>
            <a-button
              type="primary"
              icon="PlusCircleOutlined"
              size="default"
              @click="addTemporary"
              v-show='model.procurementType == 0'
            >
              临时新增
            </a-button>
              <a-button
                type="primary"
                icon="PlusCircleOutlined"
                size="default"
                @click=""
                v-show='model.procurementType == 1'
              >
                营销订单
              </a-button>

            </a-space>
          </a-col>
          <a-col :span="12">

          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <vxe-table
              border
              resizable
              show-overflow
              ref="xTable"
              :edit-config="{trigger: 'click', mode: 'cell',showStatus: true, icon: 'fa fa-pencil'}"
              :checkbox-config="{labelField: 'id'}"
              :data="model.detaillist"
              @edit-closed="editClosedEvent">
<!--              <vxe-table-column type="checkbox" title="ID" tree-node></vxe-table-column>-->
              <vxe-table-column type="seq" width="60"></vxe-table-column>
              <vxe-table-column field="materialCode" title="物料编号" ></vxe-table-column>
              <vxe-table-column field="materialName" title="名称" ></vxe-table-column>
              <vxe-table-column field="spec" title="规格" ></vxe-table-column>
              <vxe-table-column field="meUnit" :filters="dict.unit" title="单位" :formatter="['formatSelect',dict.unit]"></vxe-table-column>
              <vxe-table-column field="arrivalDate" width="120" title="到货日期" :edit-render="{name: '$input',props: {type: 'date'}}"></vxe-table-column>
              <vxe-table-column field="procurementArrayPrice" title="到货价格"  :edit-render="{name: 'input'}"></vxe-table-column>
              <vxe-table-column field="procurementNum" title="采购数量"  :edit-render="{name: '$input', props: {type: 'number'}}"></vxe-table-column>
              <vxe-table-column field="generatedNum" title="已生成订单数量" ></vxe-table-column>
              <vxe-table-column field="remainderNum" title="剩余数量" ></vxe-table-column>
              <vxe-table-column field="planNum" title="数量" ></vxe-table-column>
              <vxe-table-column field="planCode" title="原料采购计划编号" ></vxe-table-column>
              <vxe-table-column title="操作" width="100" show-overflow>
                <template v-slot="{ row }">
<!--                  <template v-if="$refs.xTable.isActiveByRow(row)">-->
<!--                    <vxe-button type="text" @click="saveRowEvent(row)">保存</vxe-button>-->
<!--                    <vxe-button type="text" @click="cancelRowEvent(row)">取消</vxe-button>-->
<!--                  </template>-->
<!--                  <template v-else>-->
<!--                    <vxe-button type="text" icon="vxe-icon&#45;&#45;edit-outline"  @click="editRowEvent(row)">编辑</vxe-button>-->
<!--                  </template>-->

<!--                  <vxe-button type="text" icon="fa fa-trash-o">删除</vxe-button>-->
                  <a-popconfirm
                        title="确认删除?"
                        @confirm="() => onDelete(row)"
                      >
                        <vxe-button type="text" icon="fa fa-trash-o">删除</vxe-button>

                      </a-popconfirm>
                              <!-- <a @click="handleEdit(record)">保存</a>-->
                </template>
              </vxe-table-column>
            </vxe-table>
            <!-- 表格 -->
<!--            <a-table bordered :data-source="model.details"-->
<!--                     tableLayout='fixed'-->
<!--                     :columns="bussMaterialProcurementDetailTable.columns"-->
<!--                     :rowKey="(record,index)=>{return index}"-->
<!--                     :pagination="false" >-->
<!--              <template slot="num" slot-scope="text, record">-->
<!--                <editable-cell :text="text" @change="onCellChange(record, 'num', $event)" ></editable-cell>-->
<!--              </template>-->
<!--&lt;!&ndash;              <template slot="arrivalDate" slot-scope="text, record">&ndash;&gt;-->
<!--&lt;!&ndash;                <editable-cell :text="text" @change="onCellChange(record, 'arrivalDate', $event)" ></editable-cell>&ndash;&gt;-->
<!--&lt;!&ndash;              </template>&ndash;&gt;-->
<!--&lt;!&ndash;              <template slot="useDesc" slot-scope="text, record">&ndash;&gt;-->
<!--&lt;!&ndash;                <editable-cell :text="text" @change="onCellChange(record, 'useDesc', $event)" ></editable-cell>&ndash;&gt;-->
<!--&lt;!&ndash;              </template>&ndash;&gt;-->
<!--              <template slot="operation" slot-scope="text, record">-->
<!--                <a-popconfirm-->
<!--                  title="确认删除?"-->
<!--                  @confirm="() => onDelete(record)"-->
<!--                >-->
<!--                  <a href="javascript:;">删除</a>-->
<!--                </a-popconfirm>-->
<!--                &lt;!&ndash; <a @click="handleEdit(record)">保存</a>&ndash;&gt;-->
<!--              </template>-->
<!--            </a-table>-->
          </a-col>
        </a-row>
      </a-tab-pane>
    </a-tabs>
    <plan-modal ref='plan' @ok='handlerok' title='采购计划单'></plan-modal>
    <erp-goods-list-model ref="selectGoodsList"
                          :category="4"
                          @handlerOk="goodsOk"
                          >
    </erp-goods-list-model>
    <erp-supplier ref='supplier' @handlerOk='initSupplier'> </erp-supplier>
  </a-spin>
</template>

<script>
  import ErpGoodsListModel from "@views/modules/goods/ErpGoodsListModal";
  import { getAction, httpAction,postAction } from '@/api/manage'
  import { FormTypes,getRefPromise,VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
  import { validateDuplicateValue } from '@/utils/util'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin'
  import ErpSupplier from './ErpSupplierList.vue'

  import PlanModal from './BussMaterialProcurementPlanList'



  export default {
    name: 'BussMaterialProcurementForm',
    mixins: [JVxeTableModelMixin],
    components: {
      ErpGoodsListModel,
      PlanModal,
      ErpSupplier
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        model:{
          detaillist: []
        },
        supplier:{

        },
        dict:{
          unit: [{label:'吨',value:'1'}]
        },
        supplyShow: true,
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
        },
        refKeys: ['bussMaterialProcurementDetail', ],
        tableKeys:['bussMaterialProcurementDetail', ],
        activeKey: 'bussMaterialProcurementDetail',
        // 原料采购订单明细
        bussMaterialProcurementDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '物料编号',
              dataIndex: 'materialCode',
            },
            {
              title: '名称',
              dataIndex: 'materialName',
            },
            {
              title: '规格',
              dataIndex: 'noneSpec',
            },
            {
              title: '单位',
              dataIndex: 'meUnit',
            },
            // {
            //   title: '采购计划单id',
            //   dataIndex: 'procurementPlanId',
            // },
            {
              title: '到货日期',
              dataIndex: 'arrivalDate'
            },
            {
              title: '到货价格',
              dataIndex: 'arrivalPrice'
            },
            {
              title: '采购数量',
              dataIndex: 'procurementNum',
            },
            {
              title: '已生成订单数量-未做',
              dataIndex: '',
            },
            {
              title: '剩余数量-未做',
              dataIndex: '',
            },
            {
              title: '数量-未做',
              dataIndex: '',
            },
            {
              title: '原料采购计划编号',
              dataIndex: 'planCode',
            },
            {
              title: '操作',
              dataIndex: 'operation',
              scopedSlots: { customRender: 'operation' },
            },
          ]
        },
        url: {
          add: "/business/bussMaterialProcurement/add",
          edit: "/business/bussMaterialProcurement/edit",
          queryById: "/business/bussMaterialProcurement/queryById",
          bussMaterialProcurementDetail: {
            list: '/business/bussMaterialProcurement/queryBussMaterialProcurementDetailByMainId'
          },
          supplierUrl: "/base/erpSupplier/queryById",
          computeUrl: "/business/bussMaterialProcurement/compute/quantity"
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
      displaySupplier(){
        // console.log('ceshi',this.supplier && this.supplier.id)
        return  typeof this.supplier.id !== "undefined" ;
      }
    },
    created () {

    },
    mounted() {
      setTimeout(function () {
        if(!this.model.code && typeof this.getPfCode === 'function'){
          this.getPfCode();
        }
      }, 500);

      //获取 数据字典
      let _this = this;
      this.getZD('ji_unit').then(res=>{
        _this.dict.unit = res
      });
    },
    methods: {
      async getZD(param){
        // 获取数据字典数据
       const res = await getAction('/sys/api/queryEnableDictItemsByCode',{code:param})
        return res;
      },
      getPfCode() {
        postAction('/sys/fillRule/executeRuleByCode/cgjhd', {}).then(res => {
          // this.model.code = res.result;
        })
      },
      editClosedEvent ({ row, column }) {
        let xTable = this.$refs.xTable
        let field = column.property
        let cellValue = row[field]
        if(row.procurementNum > row.planNum || (row.procurementNum + row.generatedNum)>row.planNum){
          this.$refs.xTable.revertData(row)
          this.$XModal.message({ message: '数量有误，请检查', status: 'warning' })
        }
        // 判断单元格值是否被修改
        if (xTable.isUpdateByRow(row, field)) {
          //计算器
          // if(row.procurementNum && row.planNum){
          this.computeQuity(row).then(res =>{
                Object.keys(res.result).forEach(key => {
                  this.$set(row, key, res.result[key]);
                });
                this.$refs.xTable.reloadRow(row, null, field)
              // this.loading = false
            })
          // }
        }
      },
      async computeQuity(param){
         const result =  await  postAction(this.url.computeUrl,param)
         return result;
      },
      addTemporary(){
        // if(!this.supplier.id){
        //   this.$XModal.message({ message: '请先选择供应商', status: 'warning' })
        //   return;
        // }
        //临时新增
        if(this.model.detaillist && this.model.detaillist.length>0 && this.model.detaillist[0].planCode){
          this.$XModal.message({ message: '临时不能与计划混加', status: 'warning' })
          return;
        }
        this.$nextTick(()=>{
          this.$refs.selectGoodsList.add();
        })
      },
      handlerok(record){
        if(!record){
          return;
        }
        console.log(record)
        if(this.model.detaillist && this.model.detaillist.length>0){
          let item = this.model.detaillist.find(item => item.procurementPlanId === record.detailId)
          if(item){
            this.$message.warning('该计划单已选择！')
            return;
          }
        }
        let isPush = true;
        let _this = this;
        let detail = {};
        detail.materialName = record.materialName
        detail.materialCode = record.materialCode
        detail.materialId = record.materialId
        detail.planCode =  record.code
        // detail.materialId = record.id
        detail.planNum = record.num;
        detail.spec = record.spec
        detail.meUnit = record.meUnit
        detail.procurementPlanId = record.detailId
        detail.supplierId = record.supplierId
        // detail.unit = record.auUnit_dictText;
        detail.arrivalDate = record.arrivalDate
        if(this.model.detaillist && this.model.detaillist.length>0){
          let isPush = this.model.details.find(item=> item.procurementPlanId === record.detailId)
          if(!isPush){
            _this.$message.warning('只能选择同一个原料采购计划单')
            return;
          }
          // this.model.details.forEach(function(item,index,arr){
          //   if(item.materialCode == record.code){
          //     _this.$message.warning('只能选择同一个原料采购计划单')
          //     isPush = false;
          //   }
          // })
        }
        if(isPush){
          this.model.detaillist.push(detail);
          if(this.model.detaillist.length>0){
            this.loadVendor(this.model.detaillist[0].supplierId)
          }
          // 加载 已生成订单的数量+ 剩余的数量
          this.computeQuity(this.model.detaillist[this.model.detaillist.length-1]).then(res =>{
            console.log(res)
            Object.keys(res.result).forEach(key => {
              this.$set(this.model.detaillist[this.model.detaillist.length-1], key, res.result[key]);
            });
            // this.$refs.xTable.reloadRow(row, null, field)
          })
        }
      },
      onDelete(record){
        const dataSource = [...this.model.detaillist];
        this.model.detaillist = dataSource.filter(item => item !== record);
        if(this.model.detaillist || this.model.detaillist.length == 0){
          this.supplier = {};
        }
      },
      addPlan(){
        if(this.model.detaillist && this.model.detaillist.length>0 && !this.model.detaillist[0].planCode){
          this.$XModal.message({ message: '计划不能与临时混加', status: 'warning' })
          return;
        }
        //新增计划单
        this.$nextTick(()=>{
          this.$refs.plan.add();
        })
      },
      goodsOk(record){
        console.log(record)
        let _this = this;
        let detail = {};
        detail.materialName = record.name
        detail.materialCode = record.code
        detail.materialId = record.id
        detail.spec = record.noneSpec
        detail.meUnit = record.meUnit
        detail.supplierId = record.supplierId
        // detail.unit = record.auUnit_dictText;
        this.model.detaillist.push(detail);
        this.loadVendor();
      },
      loadVendor(){
        if(this.model.detaillist && this.model.detaillist.length>0 && this.model.detaillist[0].supplierId){
          // 加载供应商信息
          getAction('/base/erpSupplier/queryById',{id: this.model.detaillist[0].supplierId}).then(res =>{
            this.supplier = res.result;
            this.model.supplierId = this.supplier.id
          })
        }
      },
      selectSupplier(){
      //选择供应商
        this.$nextTick(()=>{
          this.$refs.supplier.add();
        })
      },
      initSupplier(result){
         if(this.supplier && this.supplier.id != result.id){
           this.supplier = {};
           this.model.detaillist = []
         }
         this.supplier = result
         this.model.supplierId = this.supplier.id
      },
      addBefore(){
        this.bussMaterialProcurementDetailTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      // edit(record) {
      //   if (typeof this.editBefore === 'function') this.editBefore(record)
      //   this.visible = true
      //   this.activeKey = this.refKeys[0]
      //   this.$refs.form.resetFields()
      //   // Object.assign(this.model,record)
      //   // this.$set(this.model, "id", record.procurementId)
      //   // this.$set(this.model, "code", record.applicationCode)
      //   if (typeof this.editAfter === 'function') this.editAfter(this.model)
      // },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.queryById, params, this.model,this.successBack)
        }
      },
      successBack(res){
        let { result } = res
        this.model = result;
        if(this.model.detaillist && this.model.detaillist.length>0){
          this.loadVendor();
        }
      },
      //校验所有一对一子表表单
      validateSubForm(allValues){
          return new Promise((resolve,reject)=>{
            Promise.all([
            ]).then(() => {
              resolve(allValues)
            }).catch(e => {
              if (e.error === VALIDATE_NO_PASSED) {
                // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
              } else {
                console.error(e)
              }
            })
          })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          bussMaterialProcurementDetailList: allValues.tablesValue[0].values,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      submitForm() {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if (!this.model.id) {
              httpurl += this.url.add;
              method = 'post';
            } else {
              httpurl += this.url.edit;
              method = 'put';
            }
            httpAction(httpurl, this.model, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('ok');
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
        })
      },
    }
  }
</script>

<style scoped>
</style>